import 'package:merchants/models/spu_category.dart';
import 'package:merchants/services/base-service.dart';

class CategoryService extends BaseService {
  CategoryService({required super.ref});
  Future<List<SpuCategory>> getList() async {
    print('DEBUG: 开始获取分类列表');
    final response = await get<Map<String, dynamic>>(
      '/admin/category/get-list',
      parser: (json) {
        print('DEBUG: 分类API响应: $json');
        if (json['success'] != true) {
          throw ApiException(json['message'] ?? '获取分类列表失败');
        }
        return json;
      },
    );
    final List<dynamic> records = response['data'] as List<dynamic>;
    print('DEBUG: 分类数据: $records');
    return records
        .map((json) => SpuCategory.fromJson(json as Map<String, dynamic>))
        .toList();
  }

  // 新增分类
  Future<String> createCategory(SpuCategory category) async {
    final response = await post<Map<String, dynamic>>(
      '/admin/category/create',
      body: category.toJson(),
      parser: (json) {
        if (json['success'] != true) {
          throw ApiException(json['message'] ?? '创建分类失败');
        }
        return json;
      },
    );
    return response['data']['id'];
  }

  // 更新分类
  Future<void> updateCategory(SpuCategory category) async {
    print('DEBUG: 开始更新分类，id: ${category.id}, name: ${category.name}');
    print('DEBUG: 请求体: ${category.toJson()}');
    
    await put<Map<String, dynamic>>(
      '/admin/category/${category.id}',
      body: category.toJson(),
      parser: (json) {
        print('DEBUG: 更新分类响应: $json');
        if (json['success'] != true) {
          throw ApiException(json['message'] ?? '更新分类失败');
        }
        return json;
      },
    );
    print('DEBUG: 分类更新成功');
  }

  Future<void> deleteCategory(String? id) async {
    final response = await delete<Map<String, dynamic>>(
      '/admin/category/$id',
      parser: (json) {
        if (json['success'] != true) {
          throw ApiException(json['message'] ?? '删除分类失败');
        }
        return json;
      },
    );
  }
}
